<template>
  <div class="list-wrapper">
    <!-- 联系人列表 -->
 
      <van-contact-list
        :list="list"
        @add="onAdd"
        @edit="onEdit"
      />
    <!-- 联系人编辑 -->
    <van-popup v-model="showEdit" position="bottom">
      <van-contact-edit
        :contact-info="editingContact"
        :is-edit="isEdit"
        @save="onSave"
        @delete="onDelete"
      />
    </van-popup>
    <!-- <ul>
      <li v-for="(item, index) in listData"><span>{{index + 1}}、</span>{{item.title}}</li>
    </ul> -->

  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'contactList',
  components:{},
  props:{},
  data(){
    return {
      listData: [],
      list: [],
      instance: null,  // axios 实例
      showEdit: false, // 编辑弹窗的显隐
      editingContact: {}, // 正在编辑的联系人数据
      isEdit: false,   // 新建或编辑
    }
  },
  watch:{},
  computed:{},
  methods:{
    // 获取本地 static 文件夹数据
    getData() {
      axios.get('/static/data/list.json').then(res => {
        // console.log(res);
        if (res.data.length > 0) {
          this.listData = res.data.slice(0);
        }        
      })
    },
    // 获取 list 数据
    getList() {
      this.instance.get("/contactList").then(res=> {
        this.list = res.data.data;
      }).catch(err => {
        this.$toast('请求失败请稍后重试');
      })
    },
    // 添加联系人
    onAdd() {
      this.showEdit = true;
      this.isEdit = false;
    },
    // 编辑联系人
    onEdit(item) {
      this.showEdit = true;
      this.isEdit = true;
      this.editingContact = item;
    },
    // 保存联系人
    onSave(item) {
      if(this.isEdit) {
        // 编辑保存
        this.instance.put("/contact/edit", item).then(res => {
          if (res.data.code == 200){
            this.$toast('编辑成功');
            this.showEdit = false;
            this.getList();
          }
        }).catch(() => {
          this.$toast('请求失败，请稍后重试');
        });
      } else {
        // 新建保存
        this.instance.post("/contact/new/json", item).then(res => {
          if (res.data.code == 200) {
            this.$toast('新建成功');
            this.showEdit = false;
            this.getList();
          }
        }).catch(() => {
          this.$toast('请求失败，请稍后重试');
        });
      }
    },
    // 删除联系人
    onDelete(item) {
      this.instance.delete("/contact", {
        params: {
          id: item.id
        }
      }).then(res => {
         if (res.data.code == 200){
            this.$toast('删除成功');
            this.showEdit = false;
            this.getList();
          }
      }).catch(() => {
          this.$toast('请求失败，请稍后重试');
        });
    }

  },
  created(){
    this.instance = axios.create({
      baseURL: "http://localhost:9000/api",
      timeout: 1000
    })
    
    this.getData();
    
    },
  mounted(){
    this.getList();
  }
}
</script>
<style lang="scss" scoped>
.list-wrapper{
  ul > li {
    padding: 0 20px;
    line-height: 60px;
    font-size: 28px;
  }
}
</style>